package com.sunnada.wfs.geoserverRest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sunnada.wfs.utils.HttpUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class GeoServerRest {

    @Value("${geoserver.root.url}")
    private String geoserverRoot;
    @Value("${geoserver.user}")
    private String user;
    @Value("${geoserver.password}")
    private String password;

    private static final String WORKSPACES_URL = "rest/workspaces";
    private static final String DATASTORE_URL = "rest/workspaces/%s/datastores";
    private static final String FEATURETYPES_URL = "rest/workspaces/%s/datastores/%s/featuretypes";

    public String getWorksapces() throws IOException {
        StringBuilder url = new StringBuilder();
        url.append(geoserverRoot).append(WORKSPACES_URL);
        return HttpUtil.get(url.toString(),null,user,password);
    }

    public boolean haveWorksapce(String workspace) throws IOException {
        boolean result = false;
        if (StringUtils.isBlank(workspace)) return result;
        String workspaces = getWorksapces();
//        JSONArray jsonArray = JSONObject.parseObject(workspaces).getJSONObject("workspaces").getJSONArray("workspace");
        JSONObject temp1 = JSONObject.parseObject(workspaces);
        Object temp2 = temp1.get("workspaces");
        if(!(temp2 instanceof JSONObject)) return result;
        Object temp3 = ((JSONObject) temp2).get("workspace");
        if (!(temp3 instanceof JSONArray)) return result;
        JSONArray jsonArray  = (JSONArray) temp3;
        return arrhaveName(jsonArray,workspace);
    }

    public void createWorksapce(String workspaceBody) throws IOException {
        StringBuilder url = new StringBuilder();
        url.append(geoserverRoot).append(WORKSPACES_URL);
        HttpUtil.postString(url.toString(),workspaceBody,ContentType.APPLICATION_XML,user,password);
    }

    public String getDatastoreByWorkspace(String workspace) throws IOException {
        StringBuilder url = new StringBuilder();
        url.append(geoserverRoot).append(DATASTORE_URL);
        String temp = String.format(url.toString(),workspace);
        return HttpUtil.get(temp,null,user,password);
    }

    public boolean haveDatastore(String workspace,String datastore) throws IOException {
        boolean result = false;
        if (StringUtils.isBlank(workspace)) return result;
        if (StringUtils.isBlank(datastore)) return result;
        String datastores = getDatastoreByWorkspace(workspace);
//        JSONArray jsonArray = JSONObject.parseObject(datastores).getJSONObject("dataStores").getJSONArray("dataStore");
        JSONObject temp1 = JSONObject.parseObject(datastores);
        Object temp2 = temp1.get("dataStores");
        if(!(temp2 instanceof JSONObject)) return result;
        Object temp3 = ((JSONObject) temp2).get("dataStore");
        if (!(temp3 instanceof JSONArray)) return result;
        JSONArray jsonArray  = (JSONArray) temp3;
        return arrhaveName(jsonArray,datastore);
    }

    public void createDatastore(String workspace,String dataStoreBody) throws IOException {
        StringBuilder url = new StringBuilder();
        url.append(geoserverRoot).append(DATASTORE_URL);
        String temp = String.format(url.toString(),workspace);
        HttpUtil.postString(temp,dataStoreBody,ContentType.APPLICATION_XML,user,password);
    }

    public String getFeatureTypesByWorkspaceAndStore(String workspace,String store) throws IOException {
        StringBuilder url = new StringBuilder();
        url.append(geoserverRoot).append(FEATURETYPES_URL);
        String temp = String.format(url.toString(),workspace,store);
        return HttpUtil.get(temp,null,user,password);
    }

    public boolean haveFeatureType(String workspace,String datastore,String featureType) throws IOException {
        boolean result = false;
        if (StringUtils.isBlank(workspace)) return result;
        if (StringUtils.isBlank(datastore)) return result;
        if (StringUtils.isBlank(featureType)) return result;
        String featureTypes = getFeatureTypesByWorkspaceAndStore(workspace,datastore);
        JSONObject temp1 = JSONObject.parseObject(featureTypes);
        Object temp2 = temp1.get("featureTypes");
        if(!(temp2 instanceof JSONObject)) return result;
        Object temp3 = ((JSONObject) temp2).get("featureType");
        if (!(temp3 instanceof JSONArray)) return result;
        JSONArray jsonArray  = (JSONArray) temp3;
        return arrhaveName(jsonArray,featureType);
    }

    /**
     * 发布postgis数据库中的表
     * @param workspace 工作空间
     * @param datastore 数据源
     * @param featureTypeName 表名
     * @throws IOException
     */
    public void publicTableFromPostGis(String workspace,String datastore,String featureTypeName) throws IOException{
        if (StringUtils.isBlank(workspace)) return ;
        if (StringUtils.isBlank(datastore)) return ;
        StringBuilder url = new StringBuilder();
        url.append(geoserverRoot).append(FEATURETYPES_URL);
        String temp = String.format(url.toString(),workspace,datastore);
        String featureType = String.format("<featureType><name>%s</name></featureType>",featureTypeName);
        String result = HttpUtil.postString(temp,featureType, ContentType.APPLICATION_XML,user,password);
    }

    /**
     * 查看json数组中是否存在key为name且值与参数name相同的项
     * @param jsonArray 需要校验的数组
     * @param name 校验值
     * @return 值是否存在
     */
    private boolean arrhaveName(JSONArray jsonArray,String name){
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jo = jsonArray.getJSONObject(i);
            if (name.equals(jo.get("name"))) return true;
        }
        return false;
    }

    public static void main(String[] args) throws IOException {
//        String json = "{\"workspaces\":{\"workspace\":[{\"name\":\"cite\",\"href\":\"http:\\/\\/localhost:8080\\/geoserver\\/rest\\/workspaces\\/cite.json\"},{\"name\":\"tiger\",\"href\":\"http:\\/\\/localhost:8080\\/geoserver\\/rest\\/workspaces\\/tiger.json\"},{\"name\":\"nurc\",\"href\":\"http:\\/\\/localhost:8080\\/geoserver\\/rest\\/workspaces\\/nurc.json\"},{\"name\":\"sde\",\"href\":\"http:\\/\\/localhost:8080\\/geoserver\\/rest\\/workspaces\\/sde.json\"},{\"name\":\"it.geosolutions\",\"href\":\"http:\\/\\/localhost:8080\\/geoserver\\/rest\\/workspaces\\/it.geosolutions.json\"},{\"name\":\"topp\",\"href\":\"http:\\/\\/localhost:8080\\/geoserver\\/rest\\/workspaces\\/topp.json\"},{\"name\":\"sf\",\"href\":\"http:\\/\\/localhost:8080\\/geoserver\\/rest\\/workspaces\\/sf.json\"},{\"name\":\"test\",\"href\":\"http:\\/\\/localhost:8080\\/geoserver\\/rest\\/workspaces\\/test.json\"}]}}";
//        JSONObject o = JSONObject.parseObject(json);
//        System.out.println(o.get("workspaces"));
//        o.getJSONArray("");
        GeoServerRest g = new GeoServerRest();
        g.geoserverRoot = "http://localhost:8080/geoserver/";
        g.user = "admin";
        g.password = "geoserver";
        System.out.println(g.getWorksapces());
    }
}
